import store from '@/store'
let ws = null

const baseWS = `${process.env.VUE_APP_BASE_WS}`
export function initWebSocket(uid) {
//   let userInfo = vuex.state.userInfo
  // 创建websocket
  ws = new WebSocket(`${baseWS}?uid=${uid}`)
  // 连接成功发送用户信息给后端
  ws.onopen = function(event) {
    console.log('ws 连接成功')
    console.log(event)
  }
  // 收到消息保存到vuex
  ws.onmessage = function(event) {
    const wsMsgList = store.getters.wsMsgList
    const wsMsgJson = JSON.parse(event.data)
    console.log(wsMsgJson)
    const wsMsg = `${wsMsgJson.username}:${wsMsgJson.wsMsg}`
    wsMsgList.push(wsMsg)
    console.log(wsMsgList)
    store.dispatch('addMsg', wsMsgList)
    console.log('收到消息')
    console.log(event)
  }

  // 断开连接后进行重连
  ws.onclose = function(event) {
    console.log(event)
    const token = store.getters.token
    if (token) {
      setTimeout(() => {
        initWebSocket()
      }, 5000)
    }
  }
}
// 发送消息（可以引入使用，也可以挂在到Vue原型上面使用）
export function webSocketSend(data) {
  try {
    if (ws.readyState === 1) {
      ws.send(JSON.stringify(data))
    }
  } catch (error) {
    initWebSocket()
    ws.send(JSON.stringify(data))
    console.log(error)
  }
}
